import { parse } from 'qs'
import { message } from 'antd'
import moment from 'moment'
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'
import { hashHistory } from 'dva/router'
import { queryAllAddress, getDetail, AllEstateList, allActivityList, submit, advertisementAudit } from './homeBannerDetailServ.js'
import { makeAddress } from "utils/util"

const delay = (ms) => new Promise((resolve) => {

  setTimeout(resolve, ms);

});
const defultState = {
  //推荐楼盘
  query: {
    provinceCodes: [],
    cityCodes: [],
    wholeCountry: false,
    imgUrl: [],
    dynamic: true,
    img: []
  },
  city: [],
  actionType: '',
  showGif: true,
  areaList1: [],
  projectList: [],
  gif: [
    'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/icon_banner_go1.png',
    'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/icon_banner_go2.png',
    'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/icon_banner_go3.png',
    'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/icon_banner_go4.png',
    'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/icon_banner_go5.png',
    'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/icon_banner_go6.png',
  ],
  visible: false,
  localGif: '',
  local: true,
  channelIndex: 1,
  biz: {
    1: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    2: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    3: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    4: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    5: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    6: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    7: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    9: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    10: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    11: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    12: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    13: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
    14: {
      queryForm: {},
      rowSelection_type: 'radio',
      selectedRowKeys: []
    },
  },
  hrefModalObj: {
    visible: false,
    hrefType: '',
  },
  biz2: {
    queryForm: {},
    rowSelection_type: 'radio',
  },
  currentItem: [],
  clique: '',
  btnLoading: false,
  roleArea: [],
  confirmAudit: false,
  ignoreReason: false,
  auditDesc: '',//驳回原因
  // 加载中状态
  loadingGroup:{
    '0': false,
    '-1': false,
    '1': false,
    '2': false,
  }
}

const tmpModule = {
  state: cloneDeep(defultState),
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        if ('' + tmpModule.pathname === '' + pathname) {
          dispatch({ type: 'updateStore', payload: cloneDeep(defultState) });
          dispatch({ type: 'updateStore', payload: { actionType: query.actionType, advertisementId: query.advertisementId, clique: localStorage.getItem('clique') } })
          dispatch({ type: 'getAreaList', payload: {} })
          // dispatch({type: 'getAllEstateList'})

        }
      })
    },
  },
  effects: {
    //获取省市
    *getAreaList({ payload }, { put, call, select }) {
      let { actionType, advertisementId, clique } = yield select((state) => state[tmpModule.namespace])
      const { data, success } = yield call(queryAllAddress);
      if (success) {
        let arr = []
        data.map((item, index) => {
          arr.push(item.value)
        })
        console.log(arr)
        let areaList1 = []
        if (JSON.parse(clique)) {
          let arr = [data[0]]
          let attr = [data[data.length - 1]]
          data[0] = {
            label: "北京",
            value: "110100",
            children: arr
          }
          data[data.length - 1] = {
            label: "澳门",
            value: "820000",
            children: attr
          }
        }
        // //去掉第三级，
        // areaList = makeAddress(data,2)
        areaList1 = makeAddress(data, 2)
        areaList1 = data
        areaList1.shift()

        yield put({ type: 'updateStore', payload: { areaList1, roleArea: arr } })
        if (actionType == 'detail' || actionType == 'edit') {
          yield put({ type: 'getDetail', payload: { advertisementId } })
        }

      }
    },
    //获取活动详细信息
    *getDetail({ payload }, { put, call, select }) {
      const { data, success } = yield call(getDetail, payload);

      if (success) {
        //回来的数据回显
        // debugger
        let { city, areaList1, query, biz, currentItem, roleArea } = yield select((state) => state[tmpModule.namespace])
        for (var i = 0; i < data.provinceCodes.length; i++) {
          //console.log(data.provinceCodes[i],areaList1)
          console.log(data.provinceCodes[i])
          if (roleArea.indexOf(data.provinceCodes[i]) == -1) {
            delete data.provinceCodes[i]
          }
          for (var y = 0; y < areaList1.length; y++) {
            //console.log(areaList1[y])
            if (data.provinceCodes[i] == areaList1[y].value) {
              city[i] = areaList1[y].children
              //console.log(areaList1[y])
            }
          }
        }

        console.log(data.imgUrl.split(',')[1])
        data.gifimg = data.imgUrl.split(',')[1]
        data.img = data.imgUrl.split(',')[0]
        console.log(data, '---------------')
        let hrefModalObj = {}
        hrefModalObj.linkUrl = data.linkUrl
        hrefModalObj.hrefType = data.linkType
        hrefModalObj.btnName = data.btnName
        if (data.wholeCountry) {
          data.provinceCodes = ['0']
        }

        //(1:推介 2：秒杀竞拍 3：资讯 4:外部链接 5：活动，6：预约看房，7：美房详情)
        console.log(['5', '3'].indexOf(data.linkType + "") > -1, data.linkType)
        if (['1', '6'].indexOf(data.linkType + "") > -1) {
          currentItem = [data.productId]
        } else if (['5', '3'].indexOf(data.linkType + "") > -1) {
          currentItem = [data.contentId]
        } else if (['2'].indexOf(data.linkType + "") > -1) {
          currentItem = [data.linkUrl.split('=')[1]]
        }
        hrefModalObj.params = { contentId: data.contentId, productId: data.productId }
        // console.log(city)
        yield put({ type: 'updateStore', payload: { city, query: data, hrefModalObj, currentItem } })
      }

    },

    //提交表单
    *submit({ payload }, { put, call, select }) {
      try {
        if(JSON.stringify(payload) == '{}'){
          yield put({ type: 'updateStore', payload: { btnLoading: true } })
        }
        
        let { query, hrefModalObj, actionType } = yield select((state) => state[tmpModule.namespace])
        if (query.img.length == 0) {
          message.error('请上传首页图片')
          return false
        } else if (!query.wholeCountry) {
          if (new Date(query.endDate).getTime() - new Date(query.startDate).getTime() > 15 * 24 * 3600 * 1000) {
            message.error('设置生效日期的范围最长不能超过15天')
            return false
          }
        }
        let objParmas = {}
        let params = hrefModalObj.params
        query.linkType = hrefModalObj.hrefType
        query.imgUrl = query.img + `,${query.gifimg}`
        objParmas = {
          ...cloneDeep(query),
          ...cloneDeep(hrefModalObj),
          ...params
        }
        if (objParmas.seckillActivityId) {
          objParmas.contentId = objParmas.seckillActivityId
        }
        if (objParmas.wholeCountry) {
          delete objParmas.provinceCodes
          delete objParmas.cityCodes
        }
        // debugger
        const { success, msg } = yield call(submit, { ...objParmas, type: 2 });
        if (success) {
          // 保存并提交审核
          if (JSON.stringify(payload) != '{}' && payload.AuditOk) {
            let advertisementId = msg
            yield put({ type: 'advertisementAuditsubmit', payload: { advertisementId, auditStatus: 1 } })
          } else {
            message.success(actionType == 'add' ? '新增成功' : '编辑成功')
            hashHistory.push('/home/advertisementAdmin/homeBannerList?closeTab=true')
          }

        }
        yield call(delay, 2000);
        yield put({ type: 'updateStore', payload: { btnLoading: false } })
      } catch (e) {
        console.log(e)
      }

    },
    // 审核
    *advertisementAuditsubmit({ payload }, { put, call, select }) {
      try {
        let {loadingGroup} = yield select((state) => state[tmpModule.namespace])
        loadingGroup[''+payload.auditStatus+''] = true
        yield put({ type: 'updateStore', payload: { loadingGroup: loadingGroup } })
        const { success } = yield call(advertisementAudit, payload);
        if (success) {
          message.success("操作成功");
          hashHistory.push('/home/advertisementAdmin/homeBannerList?closeTab=true')
          // put({type: 'getDetail', payload: {advertisementId}})
        }
        loadingGroup[''+payload.auditStatus+''] = false
        yield put({ type: 'updateStore', payload: { loadingGroup: loadingGroup } })

      } catch (error) {
        console.log(error)
      }
    }


  },
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      console.log(3333, preState)
      return Object.assign({}, preState, action.payload)
    },
  }
}
export default tmpModule

